import {DarkTheme, DefaultTheme, Theme} from '@react-navigation/native';
import {Appearance} from 'react-native';

const listener = [] as Array<(theme: Theme) => void>;

function updateState(elements: {[key: string]: any}, cls: any, theme: any) {
  const values = {} as {[key: string]: any};
  for (const key in elements) {
    values[key] = theme.colors[elements[key]];
  }
  cls.setState({...values});
}

const data = {
  theme: Appearance.getColorScheme() === 'dark' ? DarkTheme : DefaultTheme,
  addThemeChangeListener: (callback: (theme: Theme) => void) => {
    listener.push(callback);
  },
  setThemeColorChange(cls: any, elements: {[key: string]: any}) {
    updateState(elements, cls, data.theme);
    this.addThemeChangeListener(theme => updateState(elements, cls, theme));
  },
};

Appearance.addChangeListener(({colorScheme}) => {
  const theme = colorScheme === 'dark' ? DarkTheme : DefaultTheme;
  if (theme === data.theme) {
    return;
  }
  data.theme = theme;
  listener.forEach(callback => callback(data.theme));
});

export default data;
